package club.calong.sanniu.controller;
// 团   队: 风讯网络
// 后   端: Dopa
// 开发时间: 2021/7/25 15:26

import club.calong.sanniu.http.request.SectionRequest;
import club.calong.sanniu.http.response.Response;
import club.calong.sanniu.service.SectionService;
import club.calong.sanniu.util.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
@RequestMapping("/section")
public class SectionController {

    private final SectionService service;

    @Autowired
    public SectionController(SectionService service) {
        this.service = service;
    }

    @GetMapping
    public Response list() {

        return new Response(Response.SUCCESS, service.list(null));
    }

    @GetMapping("list/{page}/{size}")
    @PreAuthorize("hasAnyAuthority('section:select')")
    public Response list(@PathVariable("page") Integer page, @PathVariable("size") Integer size, Integer type) {

        return new Response(Response.SUCCESS, service.list(page, size, type));
    }

    @PostMapping
    @PreAuthorize("hasAnyAuthority('section:update')")
    public Response create(@RequestBody SectionRequest section) {

        if (CheckUtils.checkSection(section)) {
            section.setId(null);
            section.setSubSection(new ArrayList<String>(){{
                add(section.getSection());
            }});
            if (service.create(section)) {
                return new Response(Response.SUCCESS, Response.Message.INSERT_OK, null);
            }
            return new Response(Response.FAILURE, Response.Message.INSERT_ERROR, null);
        }
        return new Response(Response.FAILURE, Response.Message.REQUEST_ERROR, null);
    }


    @PutMapping
    @PreAuthorize("hasAnyAuthority('section:update')")
    public Response update(@RequestBody SectionRequest section) {

        if (CheckUtils.checkSection(section)) {
            if (service.update(section)) {
                return new Response(Response.SUCCESS, Response.Message.UPDATE_OK, null);
            }
            return new Response(Response.FAILURE, Response.Message.UPDATE_ERROR, null);
        }
        return new Response(Response.FAILURE, Response.Message.REQUEST_ERROR, null);
    }

    @DeleteMapping("{id}")
    @PreAuthorize("hasAnyAuthority('section:update')")
    public Response delete(@PathVariable("id") Integer id) {

        if (service.delete(id)) {
            return new Response(Response.SUCCESS, Response.Message.DELETE_OK, null);
        }
        return new Response(Response.FAILURE, Response.Message.DELETE_ERROR, null);
    }
}
